package jee.boot.encrypt.dbIntercept;

import jee.boot.encrypt.config.DataEncryptConfig;
import jee.boot.encrypt.config.IEncryptDecrypt;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Properties;

/**
 * 拦截Mybatis查询结果,对需要解密的数据进行解密
 */
@Intercepts({
        @Signature(type = ResultSetHandler.class, method = "handleResultSets", args={Statement.class})
})
@Component
public class ResultInterceptor implements Interceptor {
    private Logger logger= LoggerFactory.getLogger(getClass());
    @Autowired
    private IEncryptDecrypt encryptDecrypt;
    @Autowired
    private DataEncryptConfig dataEncryptConfig;
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object result = invocation.proceed();
        if (dataEncryptConfig.getEnableEncryptedStorage()) {
            if (Objects.isNull(result)) {
                return null;
            }
            if (result instanceof ArrayList) {
                ArrayList resultList = (ArrayList) result;
                if (CollectionUtils.isNotEmpty(resultList) && encryptDecrypt.needToDecrypt(resultList.get(0))) {
                    logger.debug("存储-拦截查询数据进行解密处理");
                    for (Object o : resultList) {
                        encryptDecrypt.decrypt(o);
                    }
                }
            } else {
                if (encryptDecrypt.needToDecrypt(result)) {
                    logger.debug("存储-拦截查询数据进行解密处理");
                    encryptDecrypt.decrypt(result);
                }
            }
        }
        return result;
    }



    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

    public static void main(String[] args) {
        System.out.println(new BigDecimal(""));
    }
}
